package com.huakai.springenv.aspect.starter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.annotation.PostConstruct;

// @Component
@Slf4j
public class BootStarter implements
        CommandLineRunner,
        ApplicationRunner,
        SmartLifecycle,
        ApplicationListener<ContextRefreshedEvent>
{
    /**
     * 运行状态
     */
    private volatile boolean running = false;

    private int order = 1;


    public int getOrder() {
        return order++;
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("bootStarter commandLineRunner run() params={} order={}",args, getOrder());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("bootStarter applicationRunner run() order={}", getOrder());
    }

    @Override
    public int getPhase() {
        return SmartLifecycle.super.getPhase();
    }

    @Override
    public void start() {
        running = true;
        log.info("bootStarter SmartLifecycle start() order={}",getOrder());
        // try {
        //     Thread.sleep(3000);
        //     log.info("bootStarter start ok");
        // } catch (InterruptedException e) {
        //     throw new RuntimeException(e);
        // }
    }

    @Override
    public void stop() {
        running = false;
        log.info("bootStarter SmartLifecycle stop() order={}",getOrder());
        try {
            Thread.sleep(3000);
            log.info("bootStarter stop ok");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @PostConstruct
    public void init() {
        log.info("bootStarter @PostConstruct init() order={}",getOrder());
    }


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("bootStarter ApplicationListener onApplicationEvent() order={}",getOrder());
    }
}
